package in.co.codedoc.cg.velocity;

import in.co.codedoc.cg.CGAnnotationProcessor;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.parser.node.Node;

public class CreateJavaFileDirective extends CGBlockDirective
{
	public CreateJavaFileDirective()
	{
		super("fully qualified java class name");
	}

	@Override
	public String getName()
	{
		return "CreateJavaFile";
	}

	@Override
	public boolean render(InternalContextAdapter context, Writer writer,
			Node node) throws IOException, ResourceNotFoundException,
			ParseErrorException, MethodInvocationException
	{
		String javaClassName = getArgument(context, node, 0);
		
		PrintWriter javaFileWriter
			= CGAnnotationProcessor.getProcessor().getEnv()
				.getFiler().createSourceFile(javaClassName);

		try
		{
			node.jjtGetChild(1).render(context, javaFileWriter);
		}
		finally
		{
			if(javaFileWriter != null)
			{
				javaFileWriter.flush();
				javaFileWriter.close();
			}
		}
		
		return true;
	}
}
